<template>
	<view class="uni-tab-bar">
		<scroll-view id="tab-bar" class="uni-swiper-tab" scroll-x :scroll-left="scrollLeft">
			<view
				v-for="(tab, index) in tabBars"
				:key="tab.ref"
				:class="['swiper-tab-list', tabIndex == index ? 'active' : '']"
				:id="tab.categoryID"
				:data-current="index"
				@click="tapTab(index)"
			>
				{{ tab.categoryName }}
			</view>
		</scroll-view>
		<swiper :current="tabIndex" class="swiper-box" duration="300" @change="changeTab">
			<swiper-item v-for="(tabItem, tabIndex) in articleList" :key="tabIndex">
				<scroll-view class="list" scroll-y @scrolltolower="loadMore(tabIndex)">
					<block v-if="tabIndex == 0">
						<swiper
							class="banner-swiper"
							:indicator-dots="tabItem.data.banners.length > 1"
							:autoplay="true"
							:interval="interval"
							:circular="true"
							:duration="300"
						>
							<swiper-item
								v-for="(banner, bannerIndex) in tabItem.data.banners"
								:key="bannerIndex"
							>
								<cover-image
									class="article-banner"
									:src="getBannerUrl(banner.picUrl)"
									@click="gotoArticleDetail(banner.openType, banner.openValue)"
								></cover-image>
							</swiper-item>
						</swiper>
					</block>
					<block
						v-for="(articleItem, articleIndex) in tabItem.data.articles"
						:key="articleIndex"
					>
						<uni-article-list
							:author="articleItem.author"
							:article="articleItem.article"
							@click="goDetail(articleItem.article)"
						></uni-article-list>
					</block>
					<view class="uni-tab-bar-loading">
						<uni-load-more
							:loadingType="tabItem.loadingText"
							:contentText="loadingText"
						></uni-load-more>
					</view>
				</scroll-view>
			</swiper-item>
		</swiper>
	</view>
</template>
<script>
import uniArticleList from '@/components/uni-artilce-list/uni-artilce-list.vue';
import uniLoadMore from '@/components/uni-load-more/uni-load-more.vue';

import { friendlyDate } from '@/common/util.js';

export default {
	components: {
		uniArticleList,
		uniLoadMore
	},
	data() {
		return {
			loadingText: {
				contentdown: '上拉加载更多',
				contentrefresh: '正在加载...',
				contentnomore: '没有更多数据了'
			},
			scrollLeft: 0,
			refreshing: false,
			refreshText: '下拉可以刷新',
			//文章列表（对应分类下）
			articleList: [],
			tabIndex: 0,
			//
			tabBars: [],
			//banner自动轮播间隔
			interval: 3000,
			//资源服务器地址
			resServerBaseUrl: 'https://a8-domain.pagoda.com.cn:11052/miResourceMgr'
		};
	},
	onLoad: function() {
		this.getDiscoveryChannelList();
	},
	computed: {},
	methods: {
		getDiscoveryChannelList() {
			let that = this;
			uni.request({
				url: 'api/v1/discovery/channel/list',
				method: 'GET',
				header: {
					'X-DEFINED-appinfo': {
						deviceID: 'device26',
						os: 'iOS 12.1.4',
						verCode: '3.3.0',
						model: 'iPhone 6s Plus',
						channel: 'TEST',
						verName: '3.3.0.0'
					}
				},
				success: result => {
					console.log(result);
					if (result.statusCode == 200) {
						const porxyStatusCode = result.data.errorCode;
						if (porxyStatusCode == 0) {
							let proxyData = result.data.data;
							console.log(
								'getDiscoveryChannelList success [data] = ' +
									JSON.stringify(proxyData)
							);
							that.tabBars = proxyData;
							that.initArticleList();
							that.getArticleList();
						} else {
							let description = result.data.description;
							uni.showToast({
								title: description,
								mask: false,
								duration: 1500
							});
						}
					}
				},
				fail: () => {},
				complete: () => {}
			});
		},
		getArticleList(pageNum = 1) {
			let that = this;
			let activeTab = that.articleList[that.tabIndex];
			let reqUrl = 'api/v1/discovery/article/list';
			activeTab.requestParams.pageNum = pageNum;
			uni.request({
				url: reqUrl,
				method: 'POST',
				data: activeTab.requestParams,
				success: res => {
					if (res.statusCode === 200) {
						const porxyStatusCode = res.data.errorCode;
						if (porxyStatusCode === 0) {
							const data = res.data.data;
							console.log('getArticleList success [data] = ' + JSON.stringify(data));
							activeTab.data = data;
							activeTab.requestParams.pageNum++;
							if (activeTab.hasNextPage == 'N') {
								that.refreshing = false;
							}
						} else {
							let description = result.data.description;
							uni.showToast({
								title: description,
								mask: false,
								duration: 1500
							});
						}
					}
				},
				fail: () => {},
				complete: () => {}
			});
		},
		goDetail(detail) {
			uni.navigateTo({
				url: '/pages/detail/detail?query=' + encodeURIComponent(JSON.stringify(detail))
			});
		},
		dislike(tabIndex, newsIndex) {
			uni.showModal({
				content: '不感兴趣？',
				success: res => {
					if (res.confirm) {
						this.articleList[tabIndex].data.splice(newsIndex, 1);
					}
				}
			});
		},
		loadMore() {
			const activeTab = this.articleList[this.tabIndex];
			let isEmptyArticleList = activeTab.data.articles.length == 0;
			if (!isEmptyArticleList) {
				this.getArticleList(2);
			}
		},
		async changeTab(event) {
			let index = event.detail.current;
			if (this.isClickChange) {
				this.tabIndex = index;
				this.isClickChange = false;
				return;
			}
			let tabBar = await this.getElSize('tab-bar');
			let tabBarScrollLeft = tabBar.scrollLeft;
			let width = 0;

			for (let i = 0; i < index; i++) {
				let result = await this.getElSize(this.tabBars[i].ref);
				width += result.width;
			}
			let winWidth = uni.getSystemInfoSync().windowWidth,
				nowElement = await this.getElSize(this.tabBars[index].ref),
				nowWidth = nowElement.width;
			if (width + nowWidth - tabBarScrollLeft > winWidth) {
				this.scrollLeft = width + nowWidth - winWidth;
			}
			if (width < tabBarScrollLeft) {
				this.scrollLeft = width;
			}
			this.isClickChange = false;
			this.tabIndex = index;

			// 首次切换后加载数据
			const activeTab = this.articleList[this.tabIndex];
			if (isEmptyArticleList) {
				this.getArticleList();
			}
		},
		getNodeSize(node) {
			return new Promise((resolve, reject) => {
				dom.getComponentRect(node, result => {
					resolve(result.size);
				});
			});
		},
		onRefresh(event) {
			this.refreshText = '正在刷新...';
			this.refreshing = true;
			this.getArticleList();
		},
		getElSize(id) {
			//得到元素的size
			return new Promise((res, rej) => {
				uni.createSelectorQuery()
					.select('#' + id)
					.fields(
						{
							size: true,
							scrollOffset: true
						},
						data => {
							res(data);
						}
					)
					.exec();
			});
		},
		async tapTab(index) {
			//点击tab-bar
			if (this.tabIndex === index) {
				return false;
			} else {
				let tabBar = await this.getElSize('tab-bar'),
					tabBarScrollLeft = tabBar.scrollLeft; //点击的时候记录并设置scrollLeft
				this.scrollLeft = tabBarScrollLeft;
				this.isClickChange = true;
				this.tabIndex = index;
				// 首次切换后加载数据
				const activeTab = this.articleList[this.tabIndex];
				if (isEmptyArticleList) {
					this.getArticleList();
				}
			}
		},
		initArticleList() {
			// 初始化列表信息
			this.tabBars.forEach(tabBar => {
				this.articleList.push({
					data: {
						hasNextPage: 'Y',
						banners: [],
						articles: []
					},
					requestParams: {
						categoryID: tabBar.categoryID,
						customerID: -1,
						pageNum: 0,
						pageSize: 10
					},
					loadingText: '加载中...'
				});
			});
		},
		getBannerUrl(url) {
			if (url.length === 0) {
				console.log('resServerBaseUrl empty');
				return '';
			}
			if (url.match('^http[s]?://.+') == null) {
				console.log('resServerBaseUrl + url' + this.resServerBaseUrl + url);
				return this.resServerBaseUrl + url;
			}
			console.log('resServerBaseUrl + url' + url);
			return url;
		}
	}
};
</script>
<style>
page {
	background-color: #ffffff;
	height: 100%;
	font-size: 11px;
	line-height: 1.8;
}

.uni-tab-bar {
	display: flex;
	flex: 1;
	flex-direction: column;
	overflow: hidden;
	text-overflow: ellipsis;
	height: 100%;
}

.uni-tab-bar .list {
	width: 100%;
	height: 100%;
}

.uni-swiper-tab {
	width: 100%;
	white-space: nowrap;
	line-height: 100upx;
	height: 80upx;

	border-bottom: 1px solid #c8c7cc;
}

.swiper-tab-list {
	font-size: 28upx;
	width: 180upx;
	display: inline-block;
	text-align: center;
	overflow: hidden;
	overflow-x: hidden;
	overflow-y: hidden;
	color: #888888;
}

.uni-tab-bar .active {
	color: #333333;
	font-size: 34upx;
}

.uni-tab-bar .swiper-box {
	flex: 1;
	width: 100%;
	height: calc(100% - 100upx);
}

.uni-tab-bar-loading {
	padding: 20upx 0;
}
.banner-swiper {
	width: 100%;
	height: 280upx;
}
</style>
